package deibay.server.backend;

import java.rmi.RemoteException;

import deibay.server.backend.clients.SessionManager;
import deibay.server.backend.core.BackendRmiServer;
import deibay.server.backend.core.EventManager;
import deibay.server.backend.core.UDPService;
import deibay.server.backend.data.DataManager;
import deibay.util.IClosable;


/**
 * @author   Joel Cordeiro
 */
public class ServerManager implements IClosable{

	private DataManager dataManager = null;	
	private EventManager eventManager = null;	
	private SessionManager sessionManager = null;	
	private BackendRmiServer backendServer = null;	
	private UDPService udpService = null;
	private State state ;
	private static ServerManager instance = null;
	
	public static enum State 
	{
		running,
		halt,
	};
	
	public static ServerManager getInstance()
	{				
		if(instance==null)
		{
			instance = new ServerManager();			
		}
		return instance;
	}
	
	public ServerManager()
	{				
		try {			
			state = ServerManager.State.running;
			eventManager = new EventManager();
			dataManager = new DataManager();
			sessionManager = new SessionManager();
			backendServer = new BackendRmiServer();			
			udpService = new UDPService();					
		} catch (RemoteException e) {
			System.err.println("Exception.. "+e.getMessage());
		}
	}		

	public void init()
	{
		eventManager.init();
		dataManager.init();
		sessionManager.init();				
		backendServer.init();
		udpService.init();
	}

	public SessionManager getSessionManager()
	{
		return this.sessionManager;
	}		
	
	public EventManager getEventManager()
	{
		return this.eventManager;
	}		
	
	public State getState()
	{
		return state;
	}
	
	public void halt()
	{
		dataManager.close();
		sessionManager.close();
		backendServer.close();
		instance = null;
	}	
	
	public void close()
	{
		
	}
	
	public void restart()
	{
		state = ServerManager.State.running;
		backendServer.restart();
		dataManager.restart();
	}

}
